<template>
  <view class="searchbar" :style="[getSearchbarStyle]">
    <view v-if="$slots.leftout || leftout" class="searchbar__left-out">
      <slot v-if="$slots.leftout" name="leftout"></slot>
      <template v-else>
        <m-icon :name="leftout" size="40" color="#262626" @click="handleClick('leftout', leftout)" />
      </template>
    </view>
    <view class="searchbar__input" :style="[getInputSearchbarStyle]">
      <view v-if="$slots.leftin || leftin" class="searchbar__left-in">
        <slot v-if="$slots.leftin" name="leftin"></slot>
        <template v-else>
          <m-icon :name="leftin" size="40" color="#ccc" @click="handleClick('leftin', leftin)" />
        </template>
      </view>
      <view
        class="searchbar__input__inner"
        :class="{ 'searchbar__input__inner--custom': $slots.default }"
        @click="handleClick('inner')"
      >
        <!-- <form action="#"> -->
        <!-- @submit.prevent="handleSubmit" -->
        <slot v-if="$slots.default" />
        <input
          v-else
          v-model="modelValue"
          :placeholder="$t(modelPlaceholder)"
          :maxlength="maxLength"
          placeholder-style="color: var(--cc);"
          class="searchbar__input-bar"
          :disabled="disabled"
          confirm-type="search"
          :adjust-position="false"
          @input="handleInput"
          @focus="handleFoucs"
          @blur="handleBlur"
          @confirm="handleSubmit"
          @keydown.enter="handleSubmit"
        />
        <!-- </form> -->
        <view v-if="clearable && modelValue.length > 0" class="searchbar__input-clear" @click="handleClear">
          <m-icon name="mask-close" size="28" color="#CCCCCC"></m-icon>
        </view>
      </view>
      <view v-if="showRightIcon && getRightinIconList && getRightinIconList.length" class="searchbar__right-in">
        <view v-for="(icon, iconIndex) in getRightinIconList" :key="iconIndex" class="searchbar__right-in__icon">
          <m-icon :name="icon" size="40" color="#ccc" @click="handleClick('rightin', icon)" />
        </view>
      </view>
    </view>
    <view v-if="$slots.rightout || rightout" class="searchbar__right-out">
      <slot v-if="$slots.rightout" name="rightout"></slot>
      <template v-else>
        <m-icon
          v-if="/^[a-zA-Z\-]*$/.test(rightout)"
          :name="rightout"
          size="40"
          color="#262626"
          @click="handleClick('rightout', rightout)"
        />
        <m-button v-else @click="handleSubmit" type="primary" size="md" style="border-radius: 10rpx">
          {{ rightout }}
        </m-button>
      </template>
    </view>
  </view>
</template>

<script lang="ts">
import { defineComponent, ref, computed, watch } from '@vue/composition-api'
import { scan } from '@/utils/scan'
import { isWeixin } from '@/utils/browser'
import { isH5 } from '@/utils/platform'
import { useRouter } from '@/hooks'
import { navToPhotograph } from '@/utils/nav-to'
import addColor from '@/utils/add-color'

export default defineComponent({
  props: {
    value: {
      type: [String, Number],
      default: '',
    },
    inputType: {
      type: String,
      default: 'text',
    },
    maxLength: {
      type: [String, Number],
      default: '9999',
    },
    placeholder: {
      type: String,
      default: '请输入',
    },
    clearable: {
      type: Boolean,
      default: true,
    },
    background: {
      type: String,
      default: '#fff',
    },
    inputBackground: {
      type: String,
      default: '#f5f5f5',
    },
    inputBorder: {
      type: String,
      default: '#D8DDE1',
    },
    inputBorderRadius: {
      type: String,
      default: '100rpx',
    },
    inputTextAlign: {
      type: String,
      default: 'left',
    },
    leftout: {
      type: String,
      default: '',
    },
    leftin: {
      type: String,
      default: 'search',
    },
    rightin: {
      type: String,
      default: null,
    },
    showRightIcon: {
      type: Boolean,
      default: false,
    },
    rightout: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    hideScan: {
      type: Boolean,
      default: true,
    },
  },
  emits: ['input', 'focus', 'blur', 'change'],
  setup(props, { emit }) {
    const router = useRouter()
    const modelValue = ref(props.value)
    const modelPlaceholder = ref(props.placeholder)
    const handleClear = () => {
      modelValue.value = ''
      emit('input', '')
      emit('clear', '')
    }
    const handleSubmit = () => {
      emit('search', modelValue.value)
      try {
        // 收起键盘
        uni.hideKeyboard()
      } catch (e) {}
    }
    const handleScan = async () => {
      const state: any = await scan()

      if (state.errMsg === 'scanCode:ok') {
        router.push({
          name: 'SearchScanResult',
          params: {
            id: state.result,
          },
        })
      }
    }

    const handleClick = async (position, iconName) => {
      if (iconName === 'scan') {
        handleScan()
        return
      }

      if (iconName === 'photograph') {
        navToPhotograph()
        return
      }
      emit('click', position, iconName)
    }
    const getSearchbarStyle = computed(() => {
      return {
        background: addColor(props.background),
      }
    })
    const getInputSearchbarStyle = computed(() => {
      return {
        background: addColor(props.inputBackground),
        border: '1rpx solid ' + props.inputBorder,
        borderRadius: props.inputBorderRadius,
        textAlign: props.inputTextAlign,
      }
    })
    const handleInput = () => {
      emit('input', modelValue.value)
      emit('change', modelValue.value)
    }
    const handleFoucs = () => {
      emit('focus')
    }
    const handleBlur = () => {
      emit('blur')
    }
    const getRightinIconList = computed(() => {
      if (props.rightin !== null) {
        return [props.rightin]
      }

      if (props.hideScan || (isH5 && !isWeixin())) {
        return ['photograph']
      }

      return ['photograph', 'scan']
    })
    watch(
      () => props.value,
      (val) => {
        modelValue.value = val
      },
      {
        immediate: true,
      }
    )
    watch(
      () => props.placeholder,
      (val) => {
        modelPlaceholder.value = val
      },
      {
        immediate: true,
      }
    )
    return {
      modelValue,
      modelPlaceholder,
      handleClear,
      handleClick,
      handleSubmit,
      handleFoucs,
      handleBlur,
      handleInput,
      getSearchbarStyle,
      getInputSearchbarStyle,
      getRightinIconList,
    }
  },
})
</script>
<style lang="scss" scoped>
.searchbar {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 18rpx 24rpx;
  background: $--bg-content-c;
  box-sizing: border-box;
  font-size: 30rpx;

  &__left-out {
    margin-right: 16rpx;
  }

  &__input {
    display: flex;
    min-width: 0;
    height: 78rpx;
    flex: 1;
    padding: 0 0 0 26rpx;
    border-radius: 32rpx;
    // box-shadow: 0 0 8px #0000000a;
    background: $--bg-body-c;
    align-items: center;
    font-size: 30rpx;

    &__inner {
      display: flex;
      align-items: center;
      position: relative;
      width: 100%;
      height: 100%;
      overflow-x: auto;
      overflow-y: hidden;
      font-size: 30rpx;

      &--custom {
        padding-left: 8rpx;
      }
    }
  }

  &__right-in {
    margin-right: 24rpx;
    display: flex;

    &__icon {
      margin-right: 36rpx;
      position: relative;

      &::after {
        content: '';
        position: absolute;
        top: 6rpx;
        right: -18rpx;
        bottom: 6rpx;
        width: 1rpx;
        background-color: $--font-placeholder-c;
      }

      &:last-child {
        margin-right: 0;

        &::after {
          display: none;
        }
      }
    }
  }

  &__right-out {
    margin-left: 20rpx;
  }

  &__input-bar {
    width: 100%;
    min-width: 428rpx;
    padding-left: 8rpx;
    font-size: 30rpx;
    // #ifdef MP-WEIXIN
    min-width: 100rpx;
    width: calc(100% - 40rpx);
    //#endif
  }

  &__input-clear {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    z-index: 2;
    top: 50%;
    right: 0;
    width: 16px;
    height: 16px;
    margin-top: -8px;
    margin-right: 10px;

    & .nut-searchbar__nut-icon-mask-close {
      color: rgb(204, 204, 204);

      &:hover {
        cursor: pointer;
        color: rgb(104, 104, 104);
      }
    }
  }
}
</style>
